
# --- Step 1: Calculate summary stats by wave ---
table_df <- estimation_data %>%
  group_by(A) %>%
  summarise(
    Male = mean(V_1 == "Laki-laki"),
    Age = mean(V_2, na.rm = TRUE),
    `List Position` = mean(list_position_recode_plot, na.rm = TRUE),
    Secondary = mean(V_3 == "Sekolah Menengah Atas (SMA) atau sederajat", na.rm = TRUE),
    University = mean(V_3 %in% c("Diploma (D1/D2/D3)", "S1"), na.rm = TRUE),
    Postgraduate = mean(V_3 %in% c("S2", "S3"), na.rm = TRUE),
    Muslim = mean(V_5 == "Islam", na.rm = TRUE),
    Christian = mean(V_5 %in% c("Kristen (Protestan)", "Katolik"), na.rm = TRUE),
    `Other Religion` = mean(V_5 %in% c("Hindu", "Buddha", "Lainnya")),
    Javanese = mean(V_6 == "Jawa", na.rm = TRUE),
    Sundanese = mean(V_6 == "Sunda", na.rm = TRUE),
    Malay = mean(V_6 == "Melayu", na.rm = TRUE),
    Bugis = mean(V_6 == "Bugis", na.rm = TRUE),
    `Other Ethnicity` = mean(!(V_6 %in% c("Jawa", "Sunda", "Melayu", "Bugis")), na.rm = TRUE)
  ) %>%
  t() %>%
  as.data.frame() %>%
  slice(-1) %>%
  rownames_to_column("Feature") %>%
  setNames(c("Feature", "Wave 1", "Wave 2", "Wave 3")) %>%
  mutate(across(starts_with("Wave"), ~ round(as.numeric(.), 3)))

# --- Step 2: Define groupings ---
group_index <- c(
  "Basic Demographics" = 3,
  "Education" = 3,
  "Religion" = 3,
  "Ethnicity" = 5
)

# --- Step 3: Build the LaTeX table ---
tab <- table_df %>%
  kable(
    format = "latex",
    booktabs = TRUE,
    longtable = TRUE,
    escape = FALSE,
    col.names = c("Measure", "Wave 1", "Wave 2", "Wave 3"),
    align = c("l", "c", "c", "c"),
    linesep = "",
    caption = "Demographic Composition, by Survey Wave"
  ) %>%
  kable_styling(
    font_size = 9,
    latex_options = c("scale_down", "hold_position", "striped")
  ) %>%
  pack_rows(
    index = group_index,
    bold = TRUE,
    underline = TRUE,
    italic = TRUE
  )

# --- Step 4: Write to file ---
cat(tab, file = "./outputs/tables/table_a3.tex")
